<?php
/**
 * (model) 备货sku（JP站点）
 */
namespace App\Models\SsBasic;

use App\Models\Product\ProductSku;
use App\Models\Shipping\SSku;
use App\Models\Stocking\StockingSetDate;
use Illuminate\Database\Eloquent\Model;
class JpSku extends Model
{
    protected $table = 's_jp_sku';

    protected $guarded = [];

    const TYPE_SYSTEM = 1; //系统同步
    const TYPE_MANUAL = 2; //手工新建
    public static $_type = [
        self::TYPE_SYSTEM => '系统同步',
        self::TYPE_MANUAL => '手工新建'
    ];

    public function stocking_sku(){
        return $this->hasOne(JpStockingSku::class,'area_psku','area_psku');
    }

    public function shipping_sku(){
        return $this->hasOne(SSku::class,'area_psku','area_psku');
    }

    protected static function boot()
    {
        parent::boot();

        static::deleting(function ($model){
            $model->stocking_sku()->delete();
            //$model->shipping_sku()->delete();
        });
    }

    /**
     * 获取最快可售天数 仓库发货7天，预留7天时间
     * @param $pCycle
     * @param $transportDay
     * @return int
     */
    public static function getAvailable($pCycle,$transportDay){
        return $pCycle + $transportDay + 15;
    }

    /**
     * 获取发货库存系数 仓库发货7天，预留7天时间
     * @param $transportDay
     * @return float
     */
    public static function getShipFactor($transportDay){
        return round(($transportDay + 15) / 30,3);
    }

    /**
     * 获取备货库存系数 仓库发货7天，预留7天时间
     * @param $pCycle
     * @param $transportDay
     * @return float
     */
    public static function getStockFactor($pCycle,$transportDay){
        return round(($pCycle + $transportDay + 15) / 30,3);
    }

    /**
     * 获取提货库存系数
     * @param $pCycle
     * @param $transportDay
     * @return float
     */
    public static function getSSkuFactor($pCycle,$transportDay){
        return round(($pCycle + $transportDay + 10) / 30,3);
    }

    /**
     * 添加备货，提货基础数据（国家）
     * @param $platId
     * @param $pSkuId
     * @param $airDay
     * @param $seaDay
     * @param $pCycle
     * @param $unitPrice
     */
    public static function addJpSku($platId,$pSkuId,$airDay,$seaDay,$pCycle,$unitPrice){

        $areaId = 6; //JP站点
        $countryId = 12; //JP国家

        $key = $platId.'_'.$pSkuId;
        $count = self::query()->where('area_psku',$key)->count();
        if($count == 0){
            $classifyId = ProductSku::getValueById($pSkuId,'classify_id');
            self::query()->create([
                'area_psku' => $key,
                'plat_id' => $platId,
                'area_id' => $areaId,
                'country_id' => $countryId,
                'psku_id' => $pSkuId,
                'type' => self::TYPE_SYSTEM //系统同步
            ]);
            $avg = JpSkuAvg::query()->firstOrCreate(['area_psku' => $key]);
            $estimate = JpSkuEstimate::query()->firstOrCreate(['area_psku' => $key]);
            $stock = JpSkuStock::query()->firstOrCreate(['area_psku' => $key]);
            $stockItem = [
                'fba_instant_num' => $stock->fba_instant_num ?: 0,
                'fba_transit_num' => $stock->fba_transit_num ?: 0,
                'cn_instant_num' => $stock->cn_instant_num ?: 0,
                'cn_transit_num' => $stock->cn_transit_num ?: 0,
                'os_instant_num' => $stock->os_instant_num ?: 0,
                'os_transit_num' => $stock->os_transit_num ?: 0,
            ];
            $estimateItem = [];
            for($i = 0;$i < JpSkuEstimate::ESTIMATE_NUM - 1;$i++){
                $num = $estimate->{'estimate_num'.$i} ?? 0; //赋值
                $estimateItem['estimate_num'.$i] = intval($num);
            }
            $avgItem = [
                'avg3' => $avg->avg3 ?: 0,
                'avg7' => $avg->avg7 ?: 0,
                'avg15' => $avg->avg15 ?: 0,
                'avg30' => $avg->avg30 ?: 0,
                'avg' => $avg->avg ?: 0,
            ];
            $seaSaleDays = self::getAvailable($pCycle,$seaDay);
            $item = [
                'plat_id' => $platId, //JP
                'area_id' => $areaId,
                'country_id' => $countryId,
                'psku_id' => $pSkuId,
                'purchase_cycle' => $pCycle,
                'unit_price' => $unitPrice,
                'air_day' => $airDay,
                'air_available' => self::getAvailable($pCycle,$airDay),
                'air_ship_factor' => self::getShipFactor($airDay),
                'air_stock_factor' => self::getStockFactor($pCycle,$airDay),
                'sea_day' => $seaDay,
                'sea_available' => $seaSaleDays,
                'sea_ship_factor' => self::getShipFactor($seaDay),
                'sea_stock_factor' => self::getStockFactor($pCycle,$seaDay),
                'set_date' => StockingSetDate::getSetDate($areaId,$classifyId,$seaSaleDays)
            ];

            //国家备货sku
            $stockingSku = JpStockingSku::query()->firstOrNew(
                ['area_psku' => $key],
                array_merge($item,$avgItem,$estimateItem,$stockItem)
            );
            $stockingSku->over_stock = JpStockingSku::getOverStock($stockingSku);
            $stockingSku->over_stock_value = JpStockingSku::getOverStockValue($stockingSku->over_stock,$unitPrice);
            $stockingSku->save();
        }else{
            //基础国家sku
            $jpSku = self::query()->where('area_psku',$key)->first();
            if($jpSku->type == 2){
                $jpSku->type = 1; //系统同步
                $jpSku->save();

                $avg = JpSkuAvg::query()->firstOrCreate(['area_psku' => $key]);
                $estimate = JpSkuEstimate::query()->firstOrCreate(['area_psku' => $key]);
                $stock = JpSkuStock::query()->firstOrCreate(['area_psku' => $key]);

                //国家备货sku
                $stockingSku = JpStockingSku::query()->where('area_psku',$key)->first();
                $stockingSku->fba_instant_num = $stock->fba_instant_num ?? 0;
                $stockingSku->fba_transit_num = $stock->fba_transit_num ?? 0;
                $stockingSku->cn_instant_num = $stock->cn_instant_num ?? 0;
                $stockingSku->cn_transit_num = $stock->cn_transit_num ?? 0;
                $stockingSku->os_instant_num = $stock->os_instant_num ?? 0;
                $stockingSku->os_transit_num = $stock->os_transit_num ?? 0;
                for($i = 0;$i < JpSkuEstimate::ESTIMATE_NUM - 1;$i++){
                    $num = $estimate->{'estimate_num'.$i} ?? 0; //赋值
                    $stockingSku->{'estimate_num'.$i} = intval($num);
                }
                $stockingSku->avg3 = $avg->avg3 ?? 0;
                $stockingSku->avg7 = $avg->avg7 ?? 0;
                $stockingSku->avg15 = $avg->avg15 ?? 0;
                $stockingSku->avg30 = $avg->avg30 ?? 0;
                $stockingSku->avg = $avg->avg ?? 0;
                $stockingSku->unit_price = $unitPrice;
                $stockingSku->purchase_cycle = $pCycle;
                $stockingSku->save();
                $stockingSku->over_stock = JpStockingSku::getOverStock($stockingSku);
                $stockingSku->over_stock_value = JpStockingSku::getOverStockValue($stockingSku->over_stock,$unitPrice);
                $stockingSku->save();
            }
        }
    }

}
